package com.hmsm.sys.service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.commons.lang.xwork.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;

import seamoonotp.seamoonapi;

import com.hmsm.dingtalk.User;
import com.hmsm.server.base.BaseService;
import com.hmsm.server.common.AppContextDAO;
import com.hmsm.server.common.AppContextService;
import com.hmsm.server.common.CommonUtil;
import com.hmsm.server.util.MD5;
import com.hmsm.server.util.QueryResult;
import com.hmsm.server.util.URLHelp;
import com.hmsm.server.util.Util;
import com.hmsm.sys.bean.LocalDept;
import com.hmsm.sys.dao.UserInfoDao;
import com.hmsm.sys.dto.UserDto;
import com.hmsm.sys.po.DeptInfo;
import com.hmsm.sys.po.DynamicCipherCard;
import com.hmsm.sys.po.RoleInfo;
import com.hmsm.sys.po.UserInfo;
import com.hmsm.sys.po.UserOrg;
import com.hmsm.sys.po.UserRole;
import com.lzyyj.common.BeanUtils;
import com.lzyyj.common.Page;
import com.lzyyj.gmis.base.model.Purview;
import com.lzyyj.gmis.base.service.IHaveRoleFuncs;
import com.lzyyj.gmis.base.service.IModuleService;

@SuppressWarnings("serial")
@Component
public class UserInfoService extends BaseService<UserInfo, Integer, UserInfo, RoleInfo> implements IUserService<UserInfo>,IModuleService,IHaveRoleFuncs,IUserInfoService<UserInfo, Integer> {
	
	private static final Log log = LogFactory.getLog(UserInfoService.class);
	
	@Resource
	private UserInfoDao userInfoDao;
	
	public UserInfoDao getUserInfoDao() {
		return userInfoDao;
	}

	public void setUserInfoDao(UserInfoDao userInfoDao) {
		this.userInfoDao = userInfoDao;
	}
	
	@Resource
	private DeptInfoService deptInfoService;
	
	public DeptInfoService getDeptInfoService() {
		return deptInfoService;
	}

	public void setDeptInfoService(DeptInfoService deptInfoService) {
		this.deptInfoService = deptInfoService;
	}

	@Resource
	private UserRoleService userRoleService;

	public UserRoleService getUserRoleService() {
		return userRoleService;
	}

	public void setUserRoleService(UserRoleService userRoleService) {
		this.userRoleService = userRoleService;
	}
	
	@Resource
	private UserOrgService userOrgService;

	public UserOrgService getUserOrgService() {
		return userOrgService;
	}

	public void setUserOrgService(UserOrgService userOrgService) {
		this.userOrgService = userOrgService;
	}
	
	@Resource
	private DingUserService dingUserService;

	public DingUserService getDingUserService() {
		return dingUserService;
	}

	public void setDingUserService(DingUserService dingUserService) {
		this.dingUserService = dingUserService;
	}

	@Resource
	private DynamicCipherCardService dynamicCipherCardService;
	
	public DynamicCipherCardService getDynamicCipherCardService() {
		return dynamicCipherCardService;
	}
	public void setDynamicCipherCardService(DynamicCipherCardService dynamicCipherCardService) {
		this.dynamicCipherCardService = dynamicCipherCardService;
	}

	public static final String RIGHT_USER_MANAGE = "1002";								// 用户管理权限
	
	public static final String RIGHT_USER_VIEW = "UserView";							// 用户详情查看权限
	
	public static final String SYS_USER_ADMIN = "系统用户管理员";
	
	public static final String ORG_USER_ADMIN = "组织机构用户管理员";
	
	public static final String DEPT_USER_ADMIN = "部门用户理员";
	
	private static final List<Purview> funcGroup = new ArrayList<Purview>();
	
	@Override
	public List<Purview> getFuncGroup(){
		return funcGroup;
	}

	private static final List<String> roleList = new ArrayList<String>();
	
	@Override
	public List<String> getRoleList(){
		return roleList;
	}
	
	@Override
	public String getAdminRole() {
		// 声明业务管理角色
//		return SYS_USER_ADMIN;
		return null;
	}

	public static final Map<String, String[]> roleFuncs = new HashMap<String, String[]>();
	
	@Override
	public Map<String, String[]> getRoleFuncs() {
		return roleFuncs;
	}

	public UserInfoService(){
		
		// 声明需注册的功能权限
		Purview mainPurview = new Purview("系统管理", RIGHT_SYS_GROUP, "管理系统基本配置");
		List<Purview> purvies = mainPurview.getPurviews();
		
		Purview purview = new Purview("用户管理", RIGHT_USER_MANAGE, "管理系统用户"); 
		purvies.add(purview);
		
		List<Purview> rangeList = purview.getPurviews();
		rangeList.add(new Purview("所属部门的", RIGHT_RANGE_ORG_DEPT, "所属部门范围内的"));
		rangeList.add(new Purview("所属组织机构的", RIGHT_RANGE_ORG_ORG, "所属组织机构范围内的"));
		rangeList.add(new Purview("所有的", RIGHT_RANGE_ORG_ALL, "管理所有组织机构"));
		
		funcGroup.add(mainPurview);
		
		// 申明系统用户管理员角色，并设置默认权限
		roleList.add(ADMIN_ROLE_NAME);
		roleFuncs.put(ADMIN_ROLE_NAME, new String[]{
				RIGHT_USER_MANAGE+"("+RIGHT_RANGE_ORG_DEPT+","+RIGHT_RANGE_ORG_ORG+","+RIGHT_RANGE_ORG_ALL+")"
		});
		
	}
	
	@Override
	public String getModuleName(){
		return "用户管理";
	}

	@Override
	public void start() {
	}

	@Override
	public void stop() {
	}
	
	@Override
	public UserInfo getNew(){
		return new UserInfo();
	}

	@Override
	public UserInfo getById(Integer userId) {
		return getById(userId, false);
	}

	@Override
	public UserInfo save(UserInfo object) throws Exception {
		return save(object, null, null);
	}

	@Override
	public UserInfo save(UserInfo userVo, UserInfo currentUser) throws Exception {
		return save(userVo, null, currentUser);
	}

	@Override
	public UserInfo save(UserInfo userVo, String propertyList, UserInfo currentUser) throws Exception {
		UserInfo userPo;
		if(userVo.getPkId()!=null&&userVo.getPkId()>0){
			userPo = update(userVo, propertyList);
		}else{
			if(userVo.getState()==null){
				userVo.setState(1);
			}
			if(userVo.getType()==null){
				userVo.setType(0);
			}
			if(userVo.getCreateDate()==null){
				userVo.setCreateDate(new Timestamp(System.currentTimeMillis()));
			}
			if(userVo.getEmail()==null){
				userVo.setEmail("");
			}
			if(userVo.getPassWord()==null||userVo.getPassWord().length()==0) {
				userVo.resetPassword();
			}
			userVo.setUserDept("");
			userPo = super.save(userVo);
			List<DeptInfo> userDepts = userVo.getUserDepts();
			if(userVo.getUserDepts()!=null){
				userPo.setUserDepts(new ArrayList<DeptInfo>());
				for(DeptInfo userDept:userDepts){
					if (userDept!=null&&userDept.getPkId()!=null){
						DeptInfo depart = getDeptInfoService().getById(userDept.getPkId());
						if(depart!=null){
							getDeptInfoService().loadParent(depart, -1);
							userPo.getUserDepts().add(depart);
						}
					}

				}
				userVo.updatUserDept();
				userOrgService.updateUserDepts(userVo);
			}
		}
		if (userVo.getRoles()==null){
			if(currentUser!=null) {
				getUserInfoService().loadUserRoles(userPo, currentUser);
			}
		}else{
			getUserInfoService().updateUserRoles(userVo);
		}
		return userPo;
	}

	@Override
	public UserInfo update(UserInfo userInfoVo) throws Exception {
		return update(userInfoVo, null);
	}

	@Override
	public UserInfo update(UserInfo userInfoVo, String propertyList) throws Exception {
		UserInfo userInfoPo = getById(userInfoVo.getPkId());
		
		if (userInfoPo==null){
			throw new Exception("要更新的用户不存在！(id="+userInfoVo.getPkId()+")");
		}
		copyProperties(userInfoVo, userInfoPo, propertyList);
		if ((StringUtils.isEmpty(propertyList)||(","+propertyList+",").contains(",userDepts,"))&&userInfoVo.getUserDepts()!=null){
			userOrgService.updateUserDepts(userInfoVo);
		}
		super.update(userInfoPo);
		
		return userInfoPo;
	}

	public UserInfo getById(Integer userId, boolean includeDel) {
		
		UserInfo userInfo = super.getById(userId);
		if (includeDel||userInfo!=null&&userInfo.getState()==1){
			return userInfo;
		}
		
		return null;
	}

	@Override
	public List<UserInfo> getAll() {
		UserInfo u = new UserInfo();
		u.setState(1);
		return getUserInfoDao().query(u);
	}
	
	public List<UserInfo> getUserInfoAll(String fields) {
		UserInfo u = new UserInfo();
		u.setState(1);
		List<UserInfo> list = this.getUserInfoDao().query(u);
		if (fields!=null&&fields.equals("depart")){
			for(UserInfo user:list){
				user.setDepart(getUserOrgService().getUserDepart(user.getPkId()));
			}
		}
		
		return list;
	}

	@Override
	public boolean delete(UserInfo object) throws Exception {
		deleteUserInfo((UserInfo)object);
		return true;
	}

	/**
	 * 复制用户属性，更新时不复制用户登录名
	 * @param userInfoVo
	 * @param userInfoPo
	 * @throws Exception
	 */
	private void copyProperties(UserInfo userInfoVo, UserInfo userInfoPo, String propertyList) throws Exception {
		userInfoPo.setName(userInfoVo.getName());// 设置用户姓名
		if (userInfoPo.getPkId()==null){
			userInfoPo.setUserName(userInfoVo.getUserName());// 设置用户账号
		}
		if(propertyList==null||propertyList.length()==0||(","+propertyList+",").contains("state")){
			userInfoPo.setState(userInfoVo.getState());// 设置删除标记
		}
		if(propertyList==null||propertyList.length()==0||(","+propertyList+",").contains("telPhone")){
			userInfoPo.setTelPhone(userInfoVo.getTelPhone());// 设置电话
		}
		if(propertyList==null||propertyList.length()==0||(","+propertyList+",").contains("email")){
			userInfoPo.setEmail(userInfoVo.getEmail());
		}
		if(propertyList==null||propertyList.length()==0||(","+propertyList+",").contains("address")){
			userInfoPo.setAddress(userInfoVo.getAddress());// 设置地址
		}
		if(propertyList==null||propertyList.length()==0||(","+propertyList+",").contains("idType")){
			userInfoPo.setIdType(userInfoVo.getIdType());// 设置关联ID
		}
		if(propertyList==null||propertyList.length()==0||(","+propertyList+",").contains("userDepts")){
			if(userInfoVo.getUserDepts()!=null){
				if(userInfoPo.getUserDepts()==null){
					userInfoPo.setUserDepts(new ArrayList<DeptInfo>());
				}else{
					userInfoPo.getUserDepts().clear();
				}
				for(DeptInfo userDept:userInfoVo.getUserDepts()){
					if (userDept!=null&&userDept.getPkId()!=null){
						DeptInfo depart = getDeptInfoService().getById(userDept.getPkId());
						if(depart!=null){
							getDeptInfoService().loadParent(depart, -1);
							userInfoPo.getUserDepts().add(depart);
						}
					}

				}
				userInfoPo.updatUserDept();
			}
		}
		if (userInfoVo.getPassWord()!=null&&userInfoVo.getPassWord().length()>0&&(propertyList==null||propertyList.length()==0||(","+propertyList+",").contains("passWord"))){
			userInfoPo.updatePassword(userInfoVo.getPassWord());// 设置密码
		}
		if (userInfoPo.getCreateDate()==null){
			userInfoPo.setCreateDate(new Timestamp(System.currentTimeMillis()));
		}
		if (userInfoPo.getType()==null){
			userInfoPo.setType(1);
		}
		if (userInfoPo.getIdType()==null){
			userInfoPo.setIdType("0");
		}
	}

	/**
	 * 用户登录
	 * 
	 * @param userName
	 * @param password
	 * @return
	 * @author 舒俊
	 */
	@Override
	public UserInfo login(String userName, String password) {
		UserInfo userInfo = null;
		try {
			userInfo = getByUserName(userName);
		} catch (Exception e) {
			e.printStackTrace();
		}
		userInfo = login(userInfo, password);
		return userInfo;
	}

	/**
	 * 单点登录验证
	 * @param accountSource	账号来源
	 * @param account	登录账号
	 * @param sign	登录通行字
	 * @return	如果登录成功，返回当前登录用户信息
	 */
	public UserInfo login(String accountSource, String account, String syncurl, String sign) {
		UserInfo userInfo = null;
		
		if ("userLogin".equalsIgnoreCase(accountSource)){
			if(syncurl==null){
				userInfo = login(account, sign);
			}else{
				UserInfo user = null;
				try {
					user = getByUserName(account);
				} catch (Exception e2) {
					e2.printStackTrace();
				}
				if(user!=null){
					// 同步登录验证
					String charsetName = "GBK";
		        	try {
		        		if(syncurl != null){
		        			if(syncurl.endsWith("/")){
		        				syncurl = syncurl.substring(0, syncurl.length()-1);
		        			}
		        			syncurl += "/getRtxMarkInfo.action?syncData=" + sign;
							String strResult = new URLHelp().postURL(syncurl, null, charsetName);
							String currentCode = MD5.getMD5(sign + account, charsetName);
							//比较标识是否一致
							if(StringUtils.isBlank(sign) || !StringUtils.equals(strResult, currentCode)){
								log.error("同步登录失败，标识错误，syncData:"+sign);
							}else{
								userInfo = user;
							}
		        		}
					} catch (Exception e) {
						log.error("同步登录失败，访问服务器失败！");
					}
				}else{
					log.warn("用户未找到："+account);
				}
			}
			
		}if (accountSource.equals("RTX_001")){
			UserInfo user = null;
			try {
				user = getByUserName(account);
			} catch (Exception e2) {
				e2.printStackTrace();
			}
			if(user==null){
				user = getByRelevanceUserName(accountSource,account);
			}
			if(user!=null){
				if(sign.length()>13){
					String charsetName = "GBK";
					// 提供了标准在线令牌，进行在线验证
					String strAccount = null;
					
					try {
						strAccount = URLEncoder.encode(account, charsetName);
					} catch (UnsupportedEncodingException e1) {
						e1.printStackTrace();
					}
					if (strAccount!=null){
						String rtxUrl = CommonUtil.getSysConfigMap().get("rtxurl");
						if (rtxUrl==null) {
							rtxUrl = "http://rtx.lxls.net:8012/SignAuth.cgi";
						}
						String strURL = rtxUrl + "?user=" + strAccount + "&sign=" + sign;
						
						String strResult = new URLHelp().postURL(strURL, null, charsetName);
						if("success!".equalsIgnoreCase(strResult)){
							userInfo = user;
						}
					}
					if(userInfo==null){
						log.warn("腾讯通在线验证失败！");
					}
				}else if(sign.length()==13){
					// 黑马数码腾讯通应用管理器验证
					String charsetName = "GBK";
	        		syncurl = CommonUtil.getSysConfigMap().get("syncurl");
	        		if(syncurl==null){
	        			syncurl = "http://rtx.lxls.net:8807/user";// "http://218.89.132.26:8807/user"; http://yyj01c1:8080/RtxAppManager
	        		}
		        	try {
		        		if(syncurl != null){
		        			if(syncurl.endsWith("/")){
		        				syncurl = syncurl.substring(0, syncurl.length()-1);
		        			}
		        			syncurl += "/getRtxMarkInfo.action?syncData=" + sign;
							String strResult = new URLHelp().postURL(syncurl, null, charsetName);
							String currentCode = MD5.getMD5(sign + account, charsetName);
							String currentCode1 = MD5.getMD5(sign + account);
							//比较标识是否一致
							if(StringUtils.isBlank(sign) || !StringUtils.equals(strResult, currentCode)){
								log.error("通过RTX登录失败，腾讯通标识错误，syncDataKey:"+sign+" syncData="+strResult+" == "+currentCode + " "+currentCode1);
							}else{
								userInfo = user;
							}
		        		}
					} catch (Exception e) {
						log.error("通过RTX登录失败，访问腾讯通服务器失败！");
					}
				}else{
					// 自定义令牌，不验证了
					userInfo = user;
				}
			}else{
				log.warn("没有找到关联用户："+account);
			}
		}
	
		userInfo = login(userInfo, null);

		return userInfo;
	}

	/**
	 * 单点登录验证
	 * @param accountSource	账号来源
	 * @param account	登录账号
	 * @param sign	登录通行字
	 * @return	如果登录成功，返回当前登录用户信息
	 */
	@Override
	public UserInfo login(String accountSource, String account, String sign) {
		UserInfo userInfo = null;
		
		if ("userLogin".equalsIgnoreCase(accountSource)){
			userInfo = login(account, sign);
		}if (accountSource.equals("RTX_001")){
			UserInfo user = getByRelevanceUserName(accountSource,account);
			if(user!=null){
				if(sign.length()>13){
					String charsetName = "GBK";
					// 提供了标准在线令牌，进行在线验证
					String strAccount = null;
					
					try {
						strAccount = URLEncoder.encode(account, charsetName);
					} catch (UnsupportedEncodingException e1) {
						e1.printStackTrace();
					}
					if (strAccount!=null){
						String rtxUrl = CommonUtil.getSysConfigMap().get("rtxurl");
						if (rtxUrl==null) {
							rtxUrl = "http://rtx.lxls.net:8012/SignAuth.cgi";
						}
						String strURL = rtxUrl + "?user=" + strAccount + "&sign=" + sign;
						
						String strResult = new URLHelp().postURL(strURL, null, charsetName);
						if("success!".equalsIgnoreCase(strResult)){
							userInfo = user;
						}
					}
					if(userInfo==null){
						log.warn("腾讯通在线验证失败！");
					}
				}else if(sign.length()==13){
					// 黑马数码腾讯通应用管理器验证
					String charsetName = "GBK";
	        		String strURL = CommonUtil.getSysConfigMap().get("syncurl");
	        		if(strURL==null){
	        			strURL = "http://rtx.lxls.net:8807/user";// "http://218.89.132.26:8807/user"; http://yyj01c1:8080/RtxAppManager
	        		}
		        	try {
		        		if(strURL != null){
		        			if(strURL.endsWith("/")){
		        				strURL = strURL.substring(0, strURL.length()-1);
		        			}
		        			strURL += "/getRtxMarkInfo.action?syncData=" + sign;
							String strResult = new URLHelp().postURL(strURL, null, charsetName);
							String currentCode = MD5.getMD5(sign + account, charsetName);
							//比较标识是否一致
							if(StringUtils.isBlank(sign) || !StringUtils.equals(strResult, currentCode)){
								log.error("通过RTX登录失败，腾讯通标识错误，syncData:"+sign);
							}else{
								userInfo = user;
							}
		        		}
					} catch (Exception e) {
						log.error("通过RTX登录失败，访问腾讯通服务器失败！");
					}
				}else{
					// 自定义令牌，不验证了
					userInfo = user;
				}
			}else{
				log.warn("没有找到关联用户："+account);
			}
		}
	
		userInfo = login(userInfo, null);

		return userInfo;
	}

	private UserInfo login(UserInfo userInfo, String password) {
		if(userInfo!=null&&password!=null){
			// 需要密码或密令卡验证
			String sninfo = "";
			Integer snCode = userInfo.getSnCode();
			if(snCode == null || snCode <= 0){
				// 未配置密令卡，只能进行密码验证
				if (!userInfo.validatePassword(password)){
					if(CommonUtil.repairSys==1){
						// 尝试用超级管理员身份进行验证
						boolean adminValidate = false;
						for(UserInfo admin:getAdmins()){
							if (admin.validatePassword(password)){
								adminValidate = true;
								log.info("管理员 "+admin.getName()+" 代理登录用户 "+userInfo.getName()+"["+userInfo.getUserName()+"] 登录成功！");
								break;
							}
						}
						if (!adminValidate){
							userInfo = null;
						}
					}else{
						userInfo = null;
					}
				}
			}else{
				// 配置有密令卡，根据系统配置选择验证方式
				if (CommonUtil.loginType == 1){
					if(!validateDynamicCipherCard(userInfo.getUserName(), password, sninfo, snCode)){
						// 尝试用管理员身份进行验证
						if(CommonUtil.repairSys==1){
							boolean adminValidate = false;
							for(UserInfo admin:getAdmins()){
								if (admin.validatePassword(password)){
									adminValidate = true;
									log.info("管理员 "+admin.getName()+" 代理登录用户 "+userInfo.getName()+"["+userInfo.getUserName()+"] 登录成功！");
									break;
								}
							}
							if (!adminValidate){
								log.warn(userInfo.getUserName() + "密码验证失败！");
								userInfo = null;
							}
						}else{
							userInfo = null;
						}
					}
				}else{
					if (!userInfo.validatePassword(password)){
						// 尝试用管理员身份进行验证
						if(CommonUtil.repairSys==1){
							boolean adminValidate = false;
							for(UserInfo admin:getAdmins()){
								if (admin.validatePassword(password)){
									adminValidate = true;
									log.info("管理员 "+admin.getName()+" 代理登录用户 "+userInfo.getName()+"["+userInfo.getUserName()+"] 登录成功！");
									break;
								}
							}
							if (!adminValidate){
								userInfo = null;
								log.warn(userInfo.getUserName() + "密码验证失败！");
							}
						}else{
							userInfo = null;
						}
					}
				}
			}
		}

		if(userInfo!=null){
			loadUserDepart(userInfo);
			try {
				getRoleInfoService().loadUserRoles(userInfo);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return userInfo;
	}

	private boolean validateDynamicCipherCard(String userName, String password, String sninfo, int snCode) {
		boolean result = false;
		
		String str;
		
		//从你的数据库中把snCode的加密字符串取出来
		DynamicCipherCard card = new DynamicCipherCard();
		card.setSnCode(snCode);
		List<DynamicCipherCard> cardList = getDynamicCipherCardService().getDynamicCipherCardDao().query(card);
		if(cardList != null && cardList.size() > 0){
			card = cardList.get(0);
			sninfo = card.getSnInfo();
		}
		//验证用户密码
		if(password.length() == 6){
			seamoonapi seamoon = new seamoonapi();
		    str = seamoon.checkpassword(sninfo, password);
			if (str.length()>3){
				log(this,"密码验证通过");
				//updatesninfo(sn,str);把更新后的字符串更新到你的数据库中（只有密码验证通过后才需要更新字符串
				card.setLastUseDate(new Timestamp(System.currentTimeMillis()));
				if(card.getUseCount()==null){
					card.setUseCount(1);
				}else{
					card.setUseCount(card.getUseCount()+1);
				}
				card.setSnInfo(str);
				try {
					getDynamicCipherCardService().update(card);
				} catch (Exception e) {
					e.printStackTrace();
				}
				result = true;
			}else if(str.equals("-1")){
				result = false;
			}else if(str.equals("0")){
				result = false;
			}else{
				result = false;
			}
			
			//同步密码接口
			str = seamoon.passwordsyn(sninfo, password);
			if (str.length() > 3){
				log(this, "密码同步成功");
				//把更新后的字符串更新到你的数据库中（只有同步成功后才需要更新字符串）
				card.setSnInfo(str);
				try {
					getDynamicCipherCardService().update(card);
				} catch (Exception e) {
					e.printStackTrace();
					result = false;
				}
			}else if(str.equals("-1")){
				result = false;
			}else if(str.equals("0")){
				result = false;
			}else {
				result = false;
			}
		}else{
			log.warn(userName + "登录失败，密令字符串有错！");
		}
		
		return result;
	}

	@Override
	public UserInfo getByRelevanceUserName(String accountSource, String account) {
		UserInfo userInfo = null;
		
		for(UserInfo user:getAll()){
			if(user.getRemark()!=null&&user.getRemark().length()>0){
				for(String ss:user.getRemark().split(";")){
					String[] dd = ss.split(":");
					if(dd.length>1){
						if(dd[0].equalsIgnoreCase(accountSource)&&dd[1].equalsIgnoreCase(account)){
							userInfo = user;
							break;
						}
					}
				}
			}
		}
		
		return userInfo;
	}

	/**
	 * 获取用户 记录
	 * 
	 * @param page
	 *            当前页
	 * @param rowsPage
	 *            每页数量 0表示获取所有数据
	 * @return
	 */
	public List<UserInfo> getUserInfoAll(int page, int rowsPage) {
		// this.getUserInfoDao().getCount();
		return this.getUserInfoDao().queryUserInfo(page, rowsPage);
	}

	/**
	 * 获取其他同名用户，用于登录名同名检查
	 * 
	 * @param userName
	 * @return
	 * @author 舒俊
	 */
	public UserInfo getUserInfoByUserCode(Integer pkId, String userName) {
		UserInfo result = null;
		UserInfo userInfo = new UserInfo();
		userInfo.setUserName(userName);
		userInfo.setState(1);
		List<UserInfo> userList = this.getUserInfoDao().query(userInfo);
		if (userList!=null) {
			for(UserInfo u:userList){
				if (!u.getPkId().equals(pkId)){
					result = u;
					break;
				}
			}
		}
		return result;
	}

	/**
	 * 获取用户 记录
	 * 
	 * @param index
	 *            当前页
	 * @param maxresult
	 *            每页数量
	 * @param userName
	 *            用户账号
	 * @param name
	 *            用户姓名
	 * @return
	 */
	public QueryResult<UserInfo> getUserInfoAll(Integer index,
			Integer maxresult, String userName, String name) {

		String whererjpql = " o.state = 1 ";
		List<String> lst = new ArrayList<String>();
		if (userName != null && !userName.trim().equals("")) {
			whererjpql = whererjpql + " and o.userName  like ?";
			lst.add("%" + userName + "%");
		}
		if (name != null && !name.trim().equals("")) {
			whererjpql = whererjpql + " and o.name  like ?";
			lst.add("%" + name + "%");
		}
		LinkedHashMap<String, String> orderby = new LinkedHashMap<String, String>();
		orderby.put("pkId", "asc");
		return this.getUserInfoDao().getScrollData(UserInfo.class, "pkId",
				index, maxresult, whererjpql, lst.toArray(), orderby);
	}

	/**
	 * 根据部门编号，获取用户信息
	 * 
	 * @param deptId
	 * @return
	 * @author 舒俊
	 */
	@Override
	public List<UserDto> getUserInfoByDeptId(int deptId) {
		Util u = new Util();
		List<UserDto> usersTemp = new ArrayList<UserDto>();
		List<UserDto> userBeans =this.getUserInfoDao().getUserInfoByDeptId(deptId);
		if(userBeans!=null){
			UserDto userBean = new UserDto();
			for (int i = 0; i < userBeans.size(); i++) {
				userBean = userBeans.get(i);
				userBean.setDeptId(deptId);
				String [] deptInfoStr = u.getSplitComplex(userBean.getUserDept(), ">");
				if(deptInfoStr.length>0){
					userBean.setDeptInfo(deptInfoStr[deptInfoStr.length-1]);
				}else{
					userBean.setDeptInfo(userBean.getUserDept());
				}
				usersTemp.add(userBean);
			}
		}
		return usersTemp;
	}

	/**
	 * 获取用户登录时间
	 * 
	 * @return
	 * @author 何杰 2013-2-20
	 */
	public String getUserLoginTime(int userId) {
		return getUserInfoDao().getUserLoginTime(userId);
	}
	
	/**
	 * 根据用户账号，查询该用户信息
	 * @param userName
	 * @return
	 * @author 舒俊
	 */
	public UserInfo getRtxUserInfoByUserName(String userName){
		UserInfo user = new UserInfo();
		user.setUserName(userName);
		List<UserInfo> userAll = this.getUserInfoDao().query(user);
		if(userAll.size()>0){
			return userAll.get(0);
		}
		return null;
	}
	
	/**
	 * 
	 *  @Description: 分页查询用户列表
	 *  @MethodName :getUserInfoList
	 *  @Author     :zhangshuai
	 *  @CreateDate :2013-7-26 下午02:33:39 
	 *  @param page 当前页
	 *  @param currentUser
	 *  @return QueryResult
	 * @throws Exception 
	 *
	 */
	@Override
	public Page<UserInfo> manage(Page<UserInfo> page, UserInfo currentUser) throws Exception{
		
		checkUserManageRitht(currentUser);

		Map<String, Object> mapResult = (Map<String, Object>) page.getCondition().get("mapResult");
		if(mapResult == null){
			mapResult = new HashMap<String, Object>();
		}
		
		Integer queryType = 0;
		if(mapResult.containsKey("queryType")){
			Object queryTypePara = mapResult.get("queryType");
			if(queryTypePara!=null){
				if(queryTypePara.getClass().isAssignableFrom(Collection.class)){
					
				}else if(queryTypePara.getClass().isArray()){
					if (String.class.isAssignableFrom(queryTypePara.getClass().getComponentType())){
						if (((String[])queryTypePara).length>0){
							queryType = Integer.parseInt(((String[])queryTypePara)[0]);
						}else if (((Integer[])queryTypePara).length>0){
							queryType = ((Integer[])queryTypePara)[0];
						}else if (((int[])queryTypePara).length>0){
							queryType = ((int[])queryTypePara)[0];
						}
					}
				}
			}
		}
		
		if(!haveAdminRight(currentUser)){
			queryType = 0;
		}
		mapResult.put("queryType", queryType);
		
		// 获取可管理部门范围
		Integer range = (Integer) page.getCondition().get("range");
		page.getCondition().put("range", range);
		
		List<Map<String, Object>> rangeTypes = new ArrayList<Map<String, Object>>();

		Map<String, Object> rangeType = new HashMap<String, Object>();
		rangeType.put("id", 1);
		rangeType.put("name", "仅直属的");
		rangeTypes.add(rangeType);

		rangeType = new HashMap<String, Object>();
		rangeType.put("id", 3);
		rangeType.put("name", "全部的");
		rangeTypes.add(rangeType);
		page.getCondition().put("rangeTypes", rangeTypes);
		
		Integer deptId = page.getFindByExample().getDeptId();
		if (deptId!=null&&deptId>0){
			DeptInfo deptInfo = getDeptInfoService().getById(deptId);
			page.getFindByExample().setDepart(deptInfo);
			if (deptInfo!=null){
				getDeptInfoService().loadParent(deptInfo, -1);
			}
		}
		
		Set<Integer> deptIds = getDeptIds(deptId, range, currentUser);
		
		page.getCondition().put("deptIds", deptIds);
		
		
		switch (queryType){
		case 2:
			page.getFindByExample().setState(2);
			page = this.getUserInfoDao().find(page);
			break;
		case 1:
			page = this.getUserInfoDao().find(page);
			for(UserInfo userInfo:page.getData()){
				loadUserDepart(userInfo);
			}
			break;
		default:
			page = this.getUserInfoDao().find(page);
			break;
		}
		for(UserInfo userInfo:page.getData()){
			loadUserDepart(userInfo, deptId, deptId==null?1:0);
			getRoleInfoService().loadUserRoles(userInfo);
		}
		
		List<DeptInfo> managedOrgList = getUserDeptSelectList(null, deptId, false, 3, currentUser);
		page.getCondition().put("managedOrgList", managedOrgList);
		
		List<Map<String, Object>> queryTypeList = (List<Map<String, Object>>) mapResult.get("queryTypeList");
		if(queryTypeList==null){
			queryTypeList = new ArrayList<Map<String, Object>>();
			Map<String, Object> item = new HashMap<String, Object>();
			item.put("id",0);
			item.put("name", "正常");
			queryTypeList.add(item);
			
			item = new HashMap<String, Object>();
			item.put("id",1);
			item.put("name", "重复");
			queryTypeList.add(item);
			
			item = new HashMap<String, Object>();
			item.put("id",2);
			item.put("name", "已删");
			queryTypeList.add(item);
			
			mapResult.put("queryTypeList", queryTypeList);
		}
		
		return page;
	}

	/**
	 * 获取可管理用户的组织机构限制范围
	 * @param deptId
	 * @param range
	 * @param currentUser
	 * @return
	 * @throws Exception 
	 */
	private Set<Integer> getDeptIds(Integer deptId, Integer range, UserInfo currentUser) throws Exception {
		Set<Integer> deptIds = null;
		
		if (haveRight(RIGHT_USER_MANAGE, currentUser)){
			// 未指定节点，不限范围，根据权限范围确定最大范围
			if(haveRightRange(currentUser, RIGHT_USER_MANAGE, RIGHT_RANGE_ORG_ALL)){
				// 拥有全部范围，不限
			}else{
				// 非全部范围，受限
				deptIds = new HashSet<Integer>();
				List<DeptInfo> userDepts = getUserOrgService().getUserDepts(currentUser);
				if (haveRightRange(currentUser, RIGHT_USER_MANAGE, RIGHT_RANGE_ORG_ORG)){
					// 拥有组织机构范围,获取当前用户相关组织机构列表
					for(DeptInfo deptInfo:userDepts){
						getDeptInfoService().loadParent(deptInfo, -1);
						LocalDept orgRootDept = null;
						List<DeptInfo> parentList = deptInfo.getParentList();
						for(int i = parentList.size()-1;i>=0;i--){
							LocalDept parent=deptInfo.getParentList().get(i);
							if (parent.isOrganization()){
								orgRootDept = parent;
							}
						}
						if (orgRootDept!=null){
							deptIds.add(orgRootDept.getPkId());
							getDeptInfoService().loadSubDepts((DeptInfo)orgRootDept, -1);
							for(Object dept:orgRootDept.getAllDepts()){
								DeptInfo subDept = (DeptInfo) dept;
								deptIds.add(subDept.getPkId());
							}
						}
					}
				}else{
					// 范围缺省值为拥有部门范围
					for(DeptInfo deptInfo:userDepts){
						deptIds.add(deptInfo.getPkId());
						getDeptInfoService().loadSubDepts(deptInfo, -1);
						for(LocalDept subDept:deptInfo.getAllDepts()){
							deptIds.add(subDept.getPkId());
						}
					}
				}
			}
			// 根据权限范围获得的最大范围
			
			// 如果指定了有效的节点及范围，缩小查询范围
			if(deptId!=null&&(deptIds==null||deptIds.contains(deptId))){
				// 指定了节点，取与权限范围的交集
				deptIds = new HashSet<Integer>();
				DeptInfo deptInfo = getDeptInfoService().getById(deptId);
				if(deptInfo!=null){
					deptIds.add(deptInfo.getPkId());
					if(range==null){
						addSubDepts(deptInfo, true, deptIds);
					}else{
						switch(range){
						case 1:
							break;
						case 2:
							addSubDepts(deptInfo, false, deptIds);
							break;
						case 3:
						default:
							addSubDepts(deptInfo, true, deptIds);
							break;
						}
					}
				}
			}
		}
		
		return deptIds;
	}

	private void addSubDepts(DeptInfo deptInfo, boolean includeOrg, Set<Integer> deptIds) {
		getDeptInfoService().loadSubDepts(deptInfo, 1);
		for(LocalDept subDept:deptInfo.getSubDepts()){
			if (includeOrg||!subDept.isOrganization()){
				deptIds.add(subDept.getPkId());
				addSubDepts((DeptInfo)subDept, includeOrg, deptIds);
			}
		}
	}
	
	/**
	 * 
	 *  @Description:绑定用户密令卡
	 *  @MethodName :bindingUserMLInfo
	 *  @Author     :yaosq
	 *  @CreateDate :2013-11-15 下午05:18:12 
	 *  @param pkId
	 *
	 */
	public void bindingUserMLInfo(int pkId,int sn){
		  this.getUserInfoDao().bindingUserMLInfo(pkId, sn);
	}
	
	/**
	 * 
	 *  @Description:解除绑定用户密令卡
	 *  @MethodName :jcBinding
	 *  @Author     :yaosq
	 *  @CreateDate :2013-11-15 下午05:18:12 
	 *  @param pkId
	 *
	 */
	public void jcBinding(int pkId) {
		 this.getUserInfoDao().jcBinding(pkId);
	}
	
	/**
	 * 删除用户信息
	 * @param user
	 * @throws Exception 
	 */
	public void deleteUserInfo(UserInfo user) throws Exception{
		if(user!=null){
			if (user.getSnCode()!=null&&user.getSnCode()>0){
				throw new Exception("该用户绑定有密钥，请收回密钥并解除绑定后再删除！");
			}
			user.setState(2);
			update(user,"state");
			
			UserOrg uo = new UserOrg();
			uo.setUserId(user.getPkId());
			List<UserOrg> uoAll = AppContextDAO.getUserOrgDao().query(uo);
			for(int i=0;i<uoAll.size();i++){
				uo = uoAll.get(i);
				uo.setState(2);
				getUserOrgService().update(uo);
			}
			UserRole ur = new UserRole();
			ur.setUserId(user.getPkId());
			List<UserRole> urAll = AppContextDAO.getUserRoleDao().query(ur);
			for(int i=0;i<urAll.size();i++){
				ur = urAll.get(i);
				ur.setState(2);
				getUserRoleService().update(ur);
			}
		}
	}
	
	/**
	 * 获取用于修改的对象
	 * @param userId
	 * @param currentUser
	 * @return
	 * @throws Exception 
	 */
	@Override
	public UserInfo getForModify(Integer userId, UserInfo currentUser) throws Exception{
		return getForModify(userId, null, currentUser);
	}

	/**
	 * 获取用于修改的对象
	 * @param userId
	 * @param deptId		当前关注部门(优先)
	 * @param currentUser
	 * @return
	 * @throws Exception 
	 */
	@Override
	public UserInfo getForModify(Integer userId, Integer deptId, UserInfo currentUser) throws Exception{
		if (currentUser==null){
			throw new Exception("未登录或登录已过期，请重新登录！");
		}
		
		checkUserManageRitht(currentUser);
		
		UserInfo userInfo;
		if(userId!=null&&userId>0){
			userInfo = getById(userId);
			loadUserDepts(userInfo, null);
		}else{
			userInfo = getNew();
			loadUserDepts(userInfo, deptId);
		}
		
		loadUserRoles(userInfo, currentUser);
		
		return userInfo;
	}

	/**
	 * 
	 * @param userInfo
	 * @param deptId	当前关注的部门(用于)
	 */
	private void loadUserDepts(UserInfo userInfo, Integer deptId) {
		DeptInfo depart = null;
		Integer userId = userInfo.getPkId();
		Integer orgId = null;
		
		DeptInfo deptInfo = null;
		if(deptId!=null&&deptId>0){
			deptInfo = getDeptInfoService().getById(deptId);
		}
		if (deptInfo!=null){
			orgId = deptInfo.getOrgId();
			getDeptInfoService().loadParent(deptInfo);
		}
		List<UserOrg> userOrgs = getUserOrgService().getUserOrgDeptsByUserId(userId, orgId);
		if(userInfo.getUserDepts()==null){
			userInfo.setUserDepts(new ArrayList<DeptInfo>());
		}else{
			userInfo.getUserDepts().clear();
		}
		for(UserOrg userOrg:userOrgs){
			if (userOrg!=null&&userOrg.getDeptId()!=null&&userOrg.getDeptId()>0){
				DeptInfo userDept = getDeptInfoService().getById(userOrg.getDeptId());
				if(userDept!=null){
					userInfo.getUserDepts().add(userDept);
					if(depart==null||depart!=null&&deptId!=null&&userOrg.getDeptId().equals(deptId))
						depart = userDept;
				}
			}
		}
		userInfo.setDepart(depart);
	}

	/**
	 * 检查用户管理权限
	 * @param currentUser
	 * @throws Exception 
	 */
	private void checkUserManageRitht(UserInfo currentUser) throws Exception {
		if (!haveRight(RIGHT_USER_MANAGE, currentUser)){
			throw new Exception("你没有用户管理权限！");
		}
	}

	public void updatePassword(String password, UserInfo currentUser) throws Exception {
		currentUser = getById(currentUser.getPkId());
		if (currentUser==null){
			throw new Exception("要重置密码的用户不存在!");
		}
		currentUser.updatePassword(password);
		super.update(currentUser);
		AppContextService.getLogInfoService().save(currentUser.getPkId(), currentUser.getUserName(), "账号：【"+currentUser.getUserName()+"】更改密码成功！");
	}

	public void resetPassword(Integer userId, UserInfo currentUser) throws Exception {
		if (!haveRight(RIGHT_USER_MANAGE, currentUser)){
			throw new Exception("你没有管理用户的权限，不能重置用户密码！");
		}
		UserInfo user = getById(userId);
		if (user==null){
			throw new Exception("要重置密码的用户不存在!");
		}
		user.resetPassword();
		super.update(user);
		AppContextService.getLogInfoService().save(currentUser.getPkId(), currentUser.getUserName(), "账号：【"+user.getUserName()+"】的密码初始化成功！");
	}

	public List<UserInfo> getAdmins() {
		List<UserInfo> list = null;
		
		UserInfo userInfo = new UserInfo();
		userInfo.setUserName("超级管理员");
		userInfo.setType(2);
		userInfo.setState(1);
		list = this.getUserInfoDao().query(userInfo);
		
		return list;
	}

	@Override
	public UserInfo getByUserName(String userName) throws Exception {
		UserInfo example = new UserInfo();
		example.setUserName(userName);
		example.setState(1);
		List<UserInfo> userInfoAll = this.getUserInfoDao().query(example);
		if (userInfoAll.size() > 0) {
			return userInfoAll.get(0);
		} else {
			example.setUserName(null);
			example.setTelPhone(userName);
			userInfoAll = this.getUserInfoDao().query(example);
			if (userInfoAll.size() > 0) {
				return userInfoAll.get(0);
			} else {
				example.setTelPhone(null);
				example.setEmail(userName);
				userInfoAll = this.getUserInfoDao().query(example);
				if (userInfoAll.size() > 0) {
					return userInfoAll.get(0);
				} else {
					return null;
				}
			}
		}
	}

	public List<DeptInfo> getUserDepts(UserInfo currentUser) {
		return getUserOrgService().getUserDepts(currentUser);
	}

	public void deleteById(int userId) throws Exception {
		UserInfo userInfoPo = getById(userId);
		if (userInfoPo==null){
			throw new Exception("要删除的用户不存在或已删除！");
		}else{
			deleteUserInfo(userInfoPo);
		}
	}

	/**
	 * 为设置用户角色而获取用户相关信息
	 * @param userInfo
	 * @param currentUser
	 * @return
	 * @throws Exception
	 */
	public void loadUserRoles(UserInfo userInfo, UserInfo currentUser) throws Exception {
		// 加载用户角色
		getRoleInfoService().loadUserRoles(userInfo);
		getRoleInfoService().loadUserRoles(currentUser);
		
		List<RoleInfo> list = new ArrayList<RoleInfo>();
		List<RoleInfo> availableRoles = new ArrayList<RoleInfo>();
		List<RoleInfo> availableRoles2 = new ArrayList<RoleInfo>();
		List<RoleInfo> allRoles = getRoleInfoService().getAllRoleInfo();
		
		// 用户已有角色
		Set<Integer> roleIds = new HashSet<Integer>();
		for (RoleInfo roleInfo : allRoles) {
			
			boolean availabel = getRoleInfoService().haveUserAuthRight(roleInfo, currentUser);

			boolean find = false;
			for (RoleInfo userRole : userInfo.getRoles()) {
				if (userRole.equals(roleInfo)) {
					roleIds.add(roleInfo.getPkId());
					find = true;
					break;
				}
			}
			
			if(find){
				if (availabel){
					availableRoles.add(roleInfo);
				}else{
					list.add(roleInfo);
				}
			}else{
				if (availabel){
					availableRoles2.add(roleInfo);
				}
			}
		}
		for(RoleInfo role:availableRoles2){
			availableRoles.add(role);
		}
		if (userInfo.getRefObject() == null) {
			userInfo.setRefObject(new HashMap<String, List<? extends Object>>());
		}
		userInfo.getRefObject().put("roleList", list);
		userInfo.getRefObject().put("availableRoles", availableRoles);
		userInfo.getRefObject().put("roleIds", new ArrayList<Integer>(roleIds));
	}

	/**
	 * 更新用户角色
	 * 
	 * @param userInfoPo
	 * @return
	 * @throws Exception
	 */
	public void updateUserRoles(UserInfo userInfoPo) throws Exception {
		getUserRoleService().updateUserRoles(userInfoPo);
	}

	/**
	 * 
	 */
	@Override
	public void loadUserDepart(UserInfo userInfo) {
		loadUserDepart(userInfo, null, 0);
	}

	public void loadUserDepart(UserInfo rtxUser, Map<Integer, DeptInfo> deptMap) {
		getUserOrgService().getUserDepts(rtxUser, null, 0, deptMap);
	}
	
	/**
	 * 
	 */
	@Override
	public void loadUserDepart(UserInfo userInfo, Integer deptId, int pattern) {
		getUserOrgService().getUserDepts(userInfo, deptId, pattern);
	}

	@Override
	public List<UserInfo> findByProperty(String propertyName, Object value, String orderBy, String propertyList, long... firstAndMaxResults) throws Exception {
		List<UserInfo> list = null;
		
		UserInfo example = new UserInfo();
		example.setState(1);
		BeanUtils.setPropertyValue(example, propertyName, value);
		list = baseDao.query(example, orderBy);
		
		return list;
	}

	@Override
	public void mergeLoginName(String loginName) throws Exception {
		List<UserInfo> users = getLzyyjBaseDao().findByProperty(UserInfo.class, "userName", loginName, "pkId");
		if (users.size() < 2) {
			throw new Exception("无效登录名或者不是重名重名登录名！");
		} else {
			UserInfo tarUser = users.get(0);
			for (int i = 1; i < users.size(); i++) {
				UserInfo srcUser = users.get(i);
				// 遍历所有其他实体，将相关引用改为保留的id
				replaceRef(UserInfo.class, "user", srcUser.getPkId(), tarUser.getPkId());
				delete(srcUser);
			}
		}
	}

	/**
	 * 合并用户
	 * @param list	要合并的用户列表
	 * @param tarUser	目标用户
	 * @throws Exception
	 */
	@Override
	public UserInfo merge(List<UserInfo> list, UserInfo tarUser) throws Exception {
		if(tarUser==null){
			// 未指定目标用户时，加载各对象的外键关联资源，以外键关联资源较多的对象为目标对象
			for (UserInfo userInfo : list) {
				userInfo.setRefObject(getRefListMap(UserInfo.class, "user", userInfo.getPkId()));
			}
			
			for (UserInfo userInfo : list) {
				if(tarUser==null||userInfo.getRefObject().size()>tarUser.getRefObject().size()||userInfo.getPassWord().length()>tarUser.getPassWord().length()){
					tarUser = userInfo;
				}
			}
		}
		
		Integer tarUserId = tarUser.getPkId(); // 用作合并后保留的目标id
		for (UserInfo userInfo : list) {
			// 排除目标用户
			if(!tarUserId.equals(userInfo.getPkId())){
				// 遍历所有其他实体，将相关引用改为保留的id
				replaceRef(UserInfo.class, "user", userInfo.getPkId(), tarUserId);
				delete(userInfo);
			}
		}
		
		return tarUser;
	}

	@Override
	public UserInfo getByDingId(String dingId) {
		UserInfo userInfo = getByIdType(dingId);
		
		return userInfo;
	}

	public UserInfo getByIdType(String idType) {
		UserInfo userInfo = new UserInfo();
		userInfo.setIdType(idType);
		userInfo.setState(1);
		List<UserInfo> userInfoAll = this.getUserInfoDao().query(userInfo);
		if (userInfoAll.size() > 0) {
			return userInfoAll.get(0);
		} else {
			return null;
		}
	}

	@Override
	public UserInfo getByTelPhone(String telPhone) {
		UserInfo userInfo = new UserInfo();
		userInfo.setTelPhone(telPhone);
		userInfo.setState(1);
		List<UserInfo> userInfoAll = this.getUserInfoDao().query(userInfo);
		if (userInfoAll.size() > 0) {
			return userInfoAll.get(0);
		} else {
			return null;
		}
	}

	@Override
	public UserInfo getCurrentUser() {
		UserInfo currentUser = null;
		
		
		
		return currentUser;
	}

	@Override
	public UserInfo get(UserInfo instance) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Map<String, List<UserInfo>> getRepLoginNameMap() throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String getUserLoginTime(Integer userId) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<Integer> getUserIdsByDeptId(Integer deptId) {
		List<Integer> list = new ArrayList<Integer>();
		
		if (deptId!=null){
			DeptInfo deptInfo = getDeptInfoService().getById(deptId);
			if (deptInfo!=null){
				getDeptInfoService().loadUsers(deptInfo);
				for(UserInfo userInfo:deptInfo.getUsers()){
					list.add(userInfo.getPkId());
				}
			}
		}
		
		return list;
	}

	@Override
	public UserInfo getForSetRoles(UserInfo entity) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int getDupLoginNameCount() {
		int count = userInfoDao.getCount();
		return count;
	}

	@Override
	public boolean haveAdminRight(UserInfo currentUser) throws Exception {
		boolean result = haveRight(RIGHT_ADMIN_MANAGE, currentUser);
		return result;
	}

	@Override
	public List<UserInfo> getUsersByDeptId(Integer deptId) {
		List<UserInfo> list = null;
		
		list = userInfoDao.getUsersByDeptId(deptId);
		
		return list;
	}
	
	/**
	 * 获取可管理用户的组织机构导航列表
	 * @param deptInfo			当前正在处理的组织机构
	 * @param currentOrg	当前选择组织机构
	 * @param includeDel
	 *            是否包含已删除对象
	 * @return
	 * @throws Exception
	 * 
	 * @param excludeId
	 * @param currentId
	 * @return
	 * @throws Exception
	 */
	public List<DeptInfo> getUserDeptSelectList(Integer excludeId, Integer currentId, boolean onlyOrg, int depth, UserInfo currentUser) throws Exception {
		List<DeptInfo> list = new ArrayList<DeptInfo>();

		DeptInfo excludeDept = null;
		if (excludeId!=null){
			excludeDept = getDeptInfoService().getById(excludeId); 
		}
		
		if (haveRight(RIGHT_USER_MANAGE, currentUser)){
			Set<Integer> deptIds = getDeptIds(currentId, null, currentUser);
			
			DeptInfo currentDept = null;
			if (currentId!=null&&(deptIds==null||deptIds.contains(currentId))){
				currentDept = getDeptInfoService().getById(currentId);
			}
			// 当前parent是否有选择
			if (currentDept != null) {
				// 当前parent有选择
				getDeptInfoService().loadParent(currentDept, -1);
				if (currentDept.getParent()!=null){
					getDeptInfoService().loadSubDepts(currentDept.getParent());
					DeptInfo exclude = null;
					for(DeptInfo subDept:currentDept.getParent().getSubDepts()){
						if (!subDept.equals(excludeDept)){
							getDeptInfoService().loadSubDepts(subDept);
						}else{
							exclude = (DeptInfo)subDept;
						}
					}
					if (exclude!=null){
						currentDept.getParent().getSubDepts().remove(exclude);
					}
					getDeptInfoService().loadSubDepts(currentDept);
					exclude = null;
					for(DeptInfo subDept:currentDept.getSubDepts()){
						if (!subDept.equals(excludeDept)){
							getDeptInfoService().loadSubDepts(subDept);
						}else{
							exclude = (DeptInfo)subDept;
						}
					}
					if (exclude!=null){
						currentDept.getSubDepts().remove(exclude);
					}
					List<DeptInfo> parentList = currentDept.getParent().getParentList();
					for(DeptInfo dept:parentList){
						// 添加有权限的上级机构
						if(deptIds==null||deptIds.contains(dept.getPkId())){
							// 添加所有上级组织机构，
							getDeptInfoService().addItem(list, excludeDept, (DeptInfo)dept);
						}
					}
					if(deptIds==null||deptIds.contains(currentDept.getParent().getPkId())){
						// 当前选择的组织机构为空，即顶级，遍历所有一级组织机构
						// 添加所有同级组织机构, 如果是当前选择组织机构，还要添加其直属下级
						getDeptInfoService().addItemAndSub(list, excludeDept, (DeptInfo)currentDept.getParent(), onlyOrg, depth);
					}else{
						getDeptInfoService().addItemAndSub(list, excludeDept, currentDept, onlyOrg, depth);
					}
				}else{
					getDeptInfoService().loadSubDepts(currentDept);
					DeptInfo exclude = null;
					for(DeptInfo subDept:currentDept.getSubDepts()){
						if (!subDept.equals(excludeDept)){
							getDeptInfoService().loadSubDepts(subDept);
						}else{
							exclude = (DeptInfo)subDept;
						}
					}
					if (exclude!=null){
						currentDept.getSubDepts().remove(exclude);
					}
					List<DeptInfo> parentList = currentDept.getParentList();
					for(DeptInfo dept:parentList){
						// 添加所有上级组织机构，
						getDeptInfoService().addItem(list, excludeDept, (DeptInfo)dept);
					}
					// 当前选择的组织机构为空，即顶级，遍历所有一级组织机构
					// 添加所有同级组织机构, 如果是当前选择组织机构，还要添加其直属下级
					getDeptInfoService().addItemAndSub(list, excludeDept, currentDept, onlyOrg, depth);
				}
			} else {
				// 当前选择的组织机构为空，即顶级，遍历所有一级组织机构
				// 添加当前上级所有同级组织机构及其直属下级
				
				if(deptIds==null){
					// 部门范围无限制
					DeptInfo deptRoot = (DeptInfo) getDeptInfoService().getById(0);
					getDeptInfoService().loadSubDepts(deptRoot);
					getDeptInfoService().addItem(list, excludeDept, deptRoot);
					List<DeptInfo> rootList = deptRoot.getSubDepts();
					for (int i = 0; i < rootList.size(); i++) {
						DeptInfo o1 = rootList.get(i);
						if (((DeptInfo)o1).getState() == 1) {
							if (rootList.size() > 1) {
								getDeptInfoService().addItemAndSub(list, excludeDept, (DeptInfo)o1, onlyOrg, 0);
							} else {
								getDeptInfoService().addItemAndSub(list, excludeDept, (DeptInfo)o1, onlyOrg, 1);
							}
						}
					}
				}else{
					// 部门范围有限制
					if (haveRightRange(currentUser, RIGHT_USER_MANAGE, RIGHT_RANGE_ORG_ORG)){
						for(DeptInfo userDept:currentUser.getUserDepts()){
							DeptInfo deptRoot = (DeptInfo) getDeptInfoService().getById(userDept.getPkId());
							deptRoot = userDept.getOrgRootDept();
							getDeptInfoService().loadSubDepts(deptRoot);
							getDeptInfoService().addItem(list, excludeDept, deptRoot);
							List<DeptInfo> rootList = deptRoot.getSubDepts();
							for (int i = 0; i < rootList.size(); i++) {
								DeptInfo o1 = rootList.get(i);
								if (((DeptInfo)o1).getState() == 1) {
									if (rootList.size() > 1) {
										getDeptInfoService().addItemAndSub(list, excludeDept, (DeptInfo)o1, onlyOrg, 0);
									} else {
										getDeptInfoService().addItemAndSub(list, excludeDept, (DeptInfo)o1, onlyOrg, 1);
									}
								}
							}
						}
					}else{
						for(DeptInfo userDept:currentUser.getUserDepts()){
							DeptInfo deptRoot = (DeptInfo) getDeptInfoService().getById(userDept.getPkId());
							getDeptInfoService().loadSubDepts(deptRoot);
							getDeptInfoService().addItem(list, excludeDept, deptRoot);
							List<DeptInfo> rootList = deptRoot.getSubDepts();
							for (int i = 0; i < rootList.size(); i++) {
								DeptInfo o1 = rootList.get(i);
								if (((DeptInfo)o1).getState() == 1) {
									if (rootList.size() > 1) {
										getDeptInfoService().addItemAndSub(list, excludeDept, (DeptInfo)o1, onlyOrg, 0);
									} else {
										getDeptInfoService().addItemAndSub(list, excludeDept, (DeptInfo)o1, onlyOrg, 1);
									}
								}
							}
						}
					}
				}
			}
		}
		
		return list;
	}
	
}
